package com.atguigu03.stream;

import org.junit.Test;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;

public class StreamAPITest1 {
    //筛选与切片
    @Test
    public void t1(){
//filter(Predict p)接受lamda，从流中排除某些元素

        List<Employee> employees = EmployeeData.getEmployees();
        Stream<Employee> stream1 = employees.stream();
        //查询＞7000工资的员工信息
        stream1.filter(employee -> employee.getSalary()>5000).forEach(System.out::println);
        System.out.println();

//limit(n) 截断流，使其元素数量不超过n
        Stream<Employee> stream2 = employees.stream();

        //获取前两个
        stream2.limit(2).forEach(System.out::println);
        System.out.println();
        Stream<Employee> stream3 = employees.stream();

        //获取大于7000工资的前两个  -  链式操作
        stream3.filter(employee -> employee.getSalary()>5000).limit(2).forEach(System.out::println);
        System.out.println();
//skip(n) 跳过元素，返回一个扔掉了前n个元素的流
        Stream<Employee> stream4 = employees.stream();
        stream4.skip(3).forEach(System.out::println);
    }
        //映射
    @Test
    public void t2(){
        //map(Function f)接收一个函数作为参数，将元素转换成其他形式或提取信息，该函数会被应用到每个元素上
        //转化为大写
        List<String> list1 = Arrays.asList("aa", "bb", "cc");
        list1.stream().map(s -> s.toUpperCase()).forEach(System.out::println);
        System.out.println();

        //练习: 获取员工姓名长度大于3的员工。
        List<Employee> employeeList = EmployeeData.getEmployees();
        employeeList.stream().filter(employee -> employee.getName().length()>=3).forEach(System.out::println);

        //练习: 获取员工姓名长度大于3的员工的姓名。
        List<Employee> employeeList1 = EmployeeData.getEmployees();
        Stream<Employee> stream = employeeList1.stream();
        //过滤之后得到的还是employee实例。映射的时候还是employee
     //   stream.filter(employee -> employee.getName().length()>=3).map(employee -> employee.getName()).forEach(System.out::println);
        //映射得到的是name，过滤的是name
        stream.map(employee -> employee.getName()).filter(name->name.length()>3).forEach(System.out::println);


    }
    //排序 sort
    @Test
    public void t3(){
        //sort()自然排序
        Integer[] arr1=new Integer[]{32,53,13,423,62,42};
        String[] arr2 =new String[]{"qq","ss","ee"};

        Stream<Integer> stream1 = Arrays.stream(arr1);
        stream1.sorted().forEach(System.out::println);
        System.out.println();
        //只有当Employee实现了Comparaable接口，才能自然排序
        List<Employee> employeeList = EmployeeData.getEmployees();
        employeeList.stream().sorted().forEach(System.out::println);
        System.out.println();
        //sort(Comparator com)定制排序
        Stream<Employee> stream = EmployeeData.getEmployees().stream();
        stream.sorted((e1,e2)->e1.age-e2.age).forEach(System.out::println);
        Arrays.stream(arr2).sorted(String::compareTo).forEach(System.out::println);


    }
}
